package com.xywh.emergency_outbound.mvp.ui.activity;

import android.Manifest;
import android.content.Intent;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.view.ViewPager;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.android.arouter.facade.annotation.Route;
import com.baidu.location.BDAbstractLocationListener;
import com.baidu.location.BDLocation;
import com.baidu.location.LocationClient;
import com.baidu.location.LocationClientOption;
import com.jess.arms.base.BaseActivity;
import com.jess.arms.base.BaseConstants;
import com.jess.arms.di.component.AppComponent;
import com.jess.arms.utils.ArmsUtils;
import com.jess.arms.utils.LogUtils;

import com.xw.repo.XEditText;
import com.xywh.emergency_outbound.R;
import com.xywh.emergency_outbound.di.component.DaggerLoginComponent;
import com.xywh.emergency_outbound.di.module.LoginModule;
import com.xywh.emergency_outbound.mvp.contract.LoginContract;
import com.xywh.emergency_outbound.mvp.presenter.LoginPresenter;
import com.xywh.emergency_outbound.mvp.ui.entity.Login;
import com.xywh.emergency_outbound.mvp.ui.util.LocationUtil;

import org.jetbrains.annotations.NotNull;

import java.util.HashMap;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import me.jessyan.armscomponent.commonres.utils.CProgressDialogUtils;
import me.jessyan.armscomponent.commonres.utils.ToolbarUtils;
import me.jessyan.armscomponent.commonsdk.core.RouterHub;
import me.jessyan.armscomponent.commonsdk.utils.Utils;
import me.jessyan.retrofiturlmanager.RetrofitUrlManager;
import pub.devrel.easypermissions.EasyPermissions;

import static com.jess.arms.utils.Preconditions.checkNotNull;


@Route(path = RouterHub.ACTIVITY_LOGIN)
public class LoginActivity extends BaseActivity<LoginPresenter> implements LoginContract.View, EasyPermissions.PermissionCallbacks {

    public LocationClient mLocationClient = null;
    @BindView(R.id.btnRight)
    ImageView mBtnRight;
    @BindView(R.id.xet_account)
    XEditText xetAccount;
    @BindView(R.id.xet_pwd)
    XEditText xetPwd;
    @BindView(R.id.btn_login)
    Button btnLogin;
    @BindView(R.id.tv_location)
    TextView tv_location;
    LocationListener mListener = new LocationListener() {
        // 如果位置发生变化，重新显示
        @Override
        public void onLocationChanged(Location location) {
            showLocation(location);
        }

        @Override
        public void onStatusChanged(String provider, int status, Bundle extras) {
        }

        @Override
        public void onProviderEnabled(String provider) {
        }

        @Override
        public void onProviderDisabled(String provider) {
        }
    };
    private String[] permissions = {Manifest.permission.CAMERA, Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.ACCESS_COARSE_LOCATION, Manifest.permission.ACCESS_FINE_LOCATION};
    private View.OnClickListener mRightListener = new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            toSettingPage();
        }
    };
    private ViewPager viewPager;
    private MyLocationListener myListener = new MyLocationListener();
    private LocationManager locationManager;
    private String locationProvider;       //位置提供器

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);

        EasyPermissions.onRequestPermissionsResult(requestCode, permissions, grantResults, this);

        if (requestCode == 104) {

        }
    }

    @Override
    public void onPermissionsGranted(int requestCode, @NonNull List<String> perms) {
        ArmsUtils.makeText(this, "相关权限获取成功");
    }

    @Override
    public void onPermissionsDenied(int requestCode, @NonNull List<String> perms) {
        ArmsUtils.makeText(this, "请同意相关权限，否则功能无法使用");
    }

    @Override
    public void setupActivityComponent(@NonNull AppComponent appComponent) {
        DaggerLoginComponent //如找不到该类,请编译一下项目
                .builder()
                .appComponent(appComponent)
                .loginModule(new LoginModule(this))
                .build()
                .inject(this);
    }

    @Override
    public int initView(@Nullable Bundle savedInstanceState) {
        return R.layout.activity_login; //如果你不需要框架帮你设置 setContentView(id) 需要自行设置,请返回 0
    }

    @Override
    public void initData(@Nullable Bundle savedInstanceState) {
        getPermission();
        ToolbarUtils.initToolbarTitleNoBack(this, getString(R.string.activity_login));
        initRightBtn();
        if (!TextUtils.isEmpty(mSharedPreferencesHelper.getString(BaseConstants.USERNAME)) && !TextUtils.isEmpty(mSharedPreferencesHelper.getString(BaseConstants.PASSWORD))) {
            xetAccount.setText(mSharedPreferencesHelper.getString(BaseConstants.USERNAME));
            xetPwd.setText(mSharedPreferencesHelper.getString(BaseConstants.PASSWORD));
        }
        if (!TextUtils.isEmpty(mSharedPreferencesHelper.getString(BaseConstants.IP)) && !TextUtils.isEmpty(mSharedPreferencesHelper.getString(BaseConstants.PORT))) {
            RetrofitUrlManager.getInstance().setGlobalDomain(getUrl());
        }
//        initBaiDuLocation();
//        gpsLocation();

    }

    private boolean getPermission() {
        if (EasyPermissions.hasPermissions(this, permissions)) {
            return true;
        } else {
//            EasyPermissions.requestPermissions(this, "需要获取您的相册、照相使用权限", 1, permissions);
            EasyPermissions.requestPermissions(this, "需要获取您的使用权限", 1, permissions);
            return false;
        }

    }

    private void initRightBtn() {
        mBtnRight.setImageDrawable(getResources().getDrawable(R.drawable.icon_setting));
        mBtnRight.setOnClickListener(mRightListener);
    }

    private void initBaiDuLocation() {
        //BDAbstractLocationListener为7.2版本新增的Abstract类型的监听接口
        //原有BDLocationListener接口暂时同步保留。具体介绍请参考后文第四步的说明
        mLocationClient = new LocationClient(getApplicationContext());
        //声明LocationClient类
        mLocationClient.registerLocationListener(myListener);
        //注册监听函数
        LocationClientOption option = new LocationClientOption();
        option.setIsNeedAddress(true);

        //可选，是否需要地址信息，默认为不需要，即参数为false
        //如果开发者需要获得当前点的地址信息，此处必须为true
        option.setLocationMode(LocationClientOption.LocationMode.Hight_Accuracy);
        //可选，设置定位模式，默认高精度
        //LocationMode.Hight_Accuracy：高精度；
        //LocationMode. Battery_Saving：低功耗；
        //LocationMode. Device_Sensors：仅使用设备；

        option.setCoorType("bd09ll");
        //可选，设置返回经纬度坐标类型，默认GCJ02
        //GCJ02：国测局坐标；
        //BD09ll：百度经纬度坐标；
        //BD09：百度墨卡托坐标；
        //海外地区定位，无需设置坐标类型，统一返回WGS84类型坐标

        option.setScanSpan(10000);
//        option.setScanSpan(60000);
        //可选，设置发起定位请求的间隔，int类型，单位ms
        //如果设置为0，则代表单次定位，即仅定位一次，默认为0
        //如果设置非0，需设置1000ms以上才有效

        option.setOpenGps(true);
        //可选，设置是否使用gps，默认false
        //使用高精度和仅用设备两种定位模式的，参数必须设置为true


        option.setLocationNotify(true);
        //可选，设置是否当GPS有效时按照1S/1次频率输出GPS结果，默认false

        option.setIgnoreKillProcess(false);
        //可选，定位SDK内部是一个service，并放到了独立进程。
        //设置是否在stop的时候杀死这个进程，默认（建议）不杀死，即setIgnoreKillProcess(true)

        option.SetIgnoreCacheException(false);
        //可选，设置是否收集Crash信息，默认收集，即参数为false

        option.setWifiCacheTimeOut(5 * 60 * 1000);
        //可选，V7.2版本新增能力
        //如果设置了该接口，首次启动定位时，会先判断当前Wi-Fi是否超出有效期，若超出有效期，会先重新扫描Wi-Fi，然后定位

        option.setEnableSimulateGps(false);
        //可选，设置是否需要过滤GPS仿真结果，默认需要，即参数为false

        mLocationClient.setLocOption(option);
        //mLocationClient为第二步初始化过的LocationClient对象
        //需将配置好的LocationClientOption对象，通过setLocOption方法传递给LocationClient对象使用
        //更多LocationClientOption的配置，请参照类参考中LocationClientOption类的详细说明


        mLocationClient.start();
        //mLocationClient为第二步初始化过的LocationClient对象
        //调用LocationClient的start()方法，便可发起定位请求
    }

    private void gpsLocation() {
        //这个可以用，需要加一个GPS信号检测，提示，提示到空旷的地方去
//                GPSManager gpsManager = new GPSManager(this);
//                gpsManager.isOpen();
//                gpsManager.getGPSConfi(this, tv_location);
        //==========================================
        //初始化
        //        LocationUtils.initLocation(this);
        //        //获取经纬度
        //        Toast.makeText(this, "经度：" + LocationUtils.longitude + " 纬度：" + LocationUtils.latitude, Toast.LENGTH_SHORT).show();
        //==========================================
        //        getLocation(this);

        //==========================================
        //这个可以用，需要加一个GPS信号检测，提示，提示到空旷的地方去
        LocationUtil.getInstance(this);
        LocationUtil.isOpenGPS();
        //        //        LocationUtil.getLocation();
        //        //        LocationUtil.getStatusListener();
        LocationUtil.formListenerGetLocation();
    }

    private void showLocation(Location location) {
        String address = "纬度：" + location.getLatitude() + "经度：" + location.getLongitude();
        Toast.makeText(this, address, Toast.LENGTH_SHORT).show();

        tv_location.setText(address + ",,,");
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (mLocationClient != null) {
            mLocationClient.stop();
        }
    }

    @Override
    public void getLoginDataSuccess(Login entityData) {

        if (entityData.getCode() == 200) {
            showMessage("登录成功");

//        mSharedPreferencesHelper.putString(BaseConstants.TOKEN, login.getData().getAccess_token());
            mSharedPreferencesHelper.putString(BaseConstants.UID, String.valueOf(entityData.getData().getID()));
            mSharedPreferencesHelper.putString(BaseConstants.USERNAME, getAccount());
            mSharedPreferencesHelper.putString(BaseConstants.NICK_NAME, entityData.getData().getName());
            mSharedPreferencesHelper.putString(BaseConstants.PASSWORD, getPwd());
//        mSharedPreferencesHelper.putString(BaseConstants.API_USER_NAME, login.getApiUserName());
//        mSharedPreferencesHelper.putString(BaseConstants.API_PWD, login.getApiPwd());
            Utils.navigation(this, RouterHub.ACTIVITY_MAIN);
            killMyself();
        } else {
            if (!TextUtils.isEmpty(entityData.getMessage()))
                showMessage(entityData.getMessage());
        }

    }

    @NotNull
    private String getAccount() {
        return xetAccount.getText().toString().trim();
    }

    @NotNull
    private String getPwd() {
        return xetPwd.getText().toString().trim();
    }

    @Override
    public void showLoading() {
                CProgressDialogUtils.showProgressDialog(this);
    }

    @Override
    public void hideLoading() {
        CProgressDialogUtils.cancelProgressDialog();

    }

    @Override
    public void showMessage(@NonNull String message) {
        checkNotNull(message);
        ArmsUtils.makeText(this, message);
    }

    @Override
    public void launchActivity(@NonNull Intent intent) {
        checkNotNull(intent);
        ArmsUtils.startActivity(intent);
    }

    @Override
    public void killMyself() {
        finish();
    }

    @OnClick(R.id.btn_login)
    public void onViewClicked() {

        if (TextUtils.isEmpty(mSharedPreferencesHelper.getString(BaseConstants.IP)) || TextUtils.isEmpty(mSharedPreferencesHelper.getString(BaseConstants.PORT))) {
            showMessage("请先设置IP和Port");
            toSettingPage();
            return;
        }
        if (TextUtils.isEmpty(getAccount())) {
            showMessage("请输入登录帐号");
            return;
        }
        if (TextUtils.isEmpty(getPwd())) {
            showMessage("请输入登录密码");
            return;
        }
        if (getPermission()) {
            getLoginData();
//            Utils.navigation(this, RouterHub.ACTIVITY_MAIN);
        }


    }

    private void toSettingPage() {
        Utils.navigation(LoginActivity.this, RouterHub.ACTIVITY_SETTING);
    }

    private void getLoginData() {
        HashMap<String, String> map = new HashMap<>();
        map.put("loginname", getAccount());
        map.put("password", getPwd());
        mPresenter.getLoginData(map);
    }

    public class MyLocationListener extends BDAbstractLocationListener {
        @Override
        public void onReceiveLocation(BDLocation location) {
            //此处的BDLocation为定位结果信息类，通过它的各种get方法可获取定位相关的全部结果
            //以下只列举部分获取经纬度相关（常用）的结果信息
            //更多结果信息获取说明，请参照类参考中BDLocation类中的说明
            if (location.getLocType() == BDLocation.TypeNetWorkLocation) {
                double latitude = location.getLatitude();    //获取纬度信息
                double longitude = location.getLongitude();    //获取经度信息
                float radius = location.getRadius();    //获取定位精度，默认值为0.0f

                String coorType = location.getCoorType();
                //获取经纬度坐标类型，以LocationClientOption中设置过的坐标类型为准

                int errorCode = location.getLocType();
                //获取定位类型、定位错误返回码，具体信息可参照类参考中BDLocation类中的说明
//            EventBus.getDefault().post(location, "setAddress");
                tv_location.setText(location.getAddrStr());
                LogUtils.debugEInfo("onReceiveLocation==" + location.getAddrStr());
            }//此处的BDLocation为定位结果信息类，通过它的各种get方法可获取定位相关的全部结果
            else if (location.getLocType() == BDLocation.TypeOffLineLocation) {
                // 离线定位成功
                Log.i("baidu_location_result", "offline location success");
                double lat = location.getLatitude();
                double lon = location.getLongitude();
                tv_location.setText("lat=" + lat + " lon=" + lon);
                showMessage("lat=" + lat + " lon" + lon);

            } else if (location.getLocType() == BDLocation.TypeGpsLocation) {
                // GPS定位成功
                Log.i("baidu_location_result", "Gps location success");
                double lat = location.getLatitude();
                double lon = location.getLongitude();
                tv_location.setText("lat=" + lat + " lon=" + lon);
                showMessage("lat=" + lat + " lon" + lon);

            } else if (location.getLocType() == BDLocation.TypeOffLineLocationFail) {
                // 离线定位失败
                Log.i("baidu_location_result", "offline location fail");
                showMessage("GPS信号弱,定位失败,请到空旷的位置重新定位。");
            } else if (location.getLocType() == BDLocation.TypeOffLineLocationNetworkFail) {
                // 离线定位失败
                Log.i("baidu_location_result", "Network location fail");
                showMessage("网络信号弱,定位失败,请检查网络状态。");
            } else {

                Log.i("baidu_location_result", "location type = " + location.getLocType());
                showMessage("location type = " + location.getLocType());

            }

        }
    }
}
